package top.zxybird.common.query;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * FieldQuery.
 * 
 * Created by zxybird on 2017/11/16.
 */
public class FieldQuery extends Query {
  protected String field;
  protected List<String> values;
  protected float boost;

  public FieldQuery(String field) {
    this(field, (List) (new ArrayList()));
  }

  public FieldQuery(String field, String... values) {
    this(field, (List) (new ArrayList(Arrays.asList(values))));
  }

  public FieldQuery(String field, List<String> values) {
    this.boost = 1.0F;
    this.field = field;
    this.values = values;
  }

  public void addQuery(String query) {
    this.values.add(query);
  }

  public String toString() {
    if (this.field != null && this.values != null && !this.values.isEmpty()) {
      StringBuilder stringBuilder = new StringBuilder(32);
      if (this.values.size() == 1) {
        stringBuilder.append(this.field).append(":").append(this.escape((String) this.values.get(0)))
            .append("^" + this.boost);
      } else {
        stringBuilder.append('(');

        for (int i = 0; i < this.values.size(); ++i) {
          String v = (String) this.values.get(i);
          if (i > 0) {
            stringBuilder.append(" ").append(BooleanQuery.Occur.OR).append(" ");
          }

          stringBuilder.append(this.field).append(":").append(this.escape(v)).append("^" + this.boost);
        }

        stringBuilder.append(')');
      }

      return stringBuilder.toString();
    } else {
      return null;
    }
  }

  public void setBoost(float boost) {
    this.boost = boost;
  }
}
